<template>
  <el-drawer v-model="drawer" class="drawer-layout" size="400px" title="数据卡延期" direction="rtl" :before-close="close"
    :close-on-click-modal="false">
    <div class="info-container">
      <div class="info-container_body">
        <div class="form-section">
          <el-form ref="refFrom" label-position="top" :model="formData">
            <AgelFormGrid :items="formItem" :span="24" :gutter="16">
            </AgelFormGrid>
          </el-form>
        </div>
      </div>
      <div class="info-container_footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup name="RecordAdd" lang="ts">
import { renewalDataCard } from '@/api/station/dataCard/index';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { data_card_type } = toRefs<any>(proxy?.useDict('data_card_type'));
const defaultModel = () => ({
  cardId: '',
  cardNo: '',
  cardType: undefined,
  pMinThreshold: '',
  softExpansion: '',
  pLowDays: '',
})
const drawer = ref(false)
const formData = reactive(defaultModel())
const formItem = ref([
  { prop: "cardNo", label: "卡号", attrs: { disabled: true, } },// TODO 验证卡号格式，并验证是否已存在
  {
    prop: "cardType", label: "类型", slot: 'agel-select', required: true,
    attrs: {
      disabled: true,
      options: data_card_type
    }
  },
  {
    prop: "expireTime", label: "有效期限", slot: 'el-date-picker',
    attrs: { type: 'date', valueFormat: 'YYYY-MM-DD hh:mm:ss', placeholder: '请选择有效期' },
  },
  {
    prop: "deviceType", label: "设备类型TODO", slot: 'agel-select',
    attrs: {
      disabled: true,
      options: data_card_type
    }
  },
  { prop: "deviceId", label: "设备编号", attrs: { disabled: true, } }, // TODO 通过编号查询出设备，若设备已绑定数据卡可进行解绑操作
],)
const loading = ref(false)
const refFrom = ref<ElFormInstance>()
const emits = defineEmits(['close', 'success'])

const openByInfo = (info) => {
  Object.assign(formData, info)
  drawer.value = true
}
/** 取消 */
const close = () => {
  drawer.value = false
  emits('close')
}
/** 确认 */
const handleSubmit = async () => {
  if (!refFrom.value) return
  refFrom.value.validate((valid, fields) => {
    if (valid) {
      requestAdd()
    } else {
      console.log('error submit!', fields)
    }
  })
}
const requestAdd = async () => {
  loading.value = true
  let res = await renewalDataCard(formData)
  loading.value = false
  if (res.code == 200) {
    proxy?.$modal.msgSuccess('操作成功！')
    emits('success')
    close()
  } else {
    proxy?.$modal.msgError(res.msg || '操作失败！')
  }
}
defineExpose({ openByInfo })
</script>
